/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.bricket.web.common;

import java.util.List;

import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.googlecode.bricket.domain.DomainObject;
import com.googlecode.bricket.repository.GenericDomainService;
import com.inmethod.grid.IDataSource;
import com.inmethod.grid.IGridSortState;
import com.inmethod.grid.IGridSortState.ISortStateColumn;

/**
 * Generischer Dataprovider für die Inmethod Grids.
 * @author Ingo Renner
 * @author Henning Teek
 *
 * @param <T>
 */
public class GenericDataSource<T extends DomainObject> implements IDataSource {
	@SpringBean
	private GenericDomainService genericDomainService;

	private final Class<T> type;

	@SuppressWarnings("unchecked")
	public GenericDataSource(T domainObject) {
		InjectorHolder.getInjector().inject(this);
		this.type = (Class<T>) domainObject.getClass();
	}

	@SuppressWarnings("unchecked")
	@Override
	public IModel<T> model(Object object) {
		return new DomainObjectModel<T>((T)object);
	}

	@Override
	public void query(IQuery query, IQueryResult result) {

		String sortProperty = null;
		boolean sortAsc = true;

		// is there any sorting
		if (query.getSortState().getColumns().size() > 0) {
			// get the most relevant column 
			ISortStateColumn state = query.getSortState().getColumns().get(0);

			// get the column sort properties
			sortProperty = state.getPropertyName();
			sortAsc = state.getDirection() == IGridSortState.Direction.ASC;
		}

		// determine the total count
		result.setTotalCount(genericDomainService.getCount(type));

		// get the actual items
		List<T> resultList = genericDomainService.loadAll(type, query.getFrom(), query.getCount(), sortProperty, sortAsc);
		result.setItems(resultList.iterator());
	}

	@Override
	public void detach() {
	}
}
